package com.swgk.core.util;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.drawable.ColorDrawable;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Environment;
import android.os.Handler;
import android.os.Looper;
import android.provider.MediaStore;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicBlur;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.TextUtils;
import android.text.method.DigitsKeyListener;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.chad.library.adapter.base.BaseViewHolder;
import com.swgk.core.R;
import com.swgk.core.event.MessageEvent;

import org.greenrobot.eventbus.EventBus;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.security.SecureRandom;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
 * 作者: zhangl
 * 时间: 2017/11/2 0002
 * 描述: UI工具类
 **/

public class UiUtil {
    /**
     * 全局的上下文
     */
    private static Context mBaseContext;
    private static Handler mHandler;
    private static PopupWindow mPopupWindow;

    public static Context getContext() {
        return mBaseContext;
    }

    public static void init(Context application) {
        mBaseContext = application;
        mHandler = new Handler();
    }

    /**
     * 提交一个任务
     */
    public static void post(Runnable task) {
        mHandler.post(task);
    }

    /**
     * 延时提交一个任务
     */
    public static void postDelay(Runnable task, long delay) {
        mHandler.postDelayed(task, delay);
    }

    /**
     * 取消一个任务
     */
    public static void cacel(Runnable task) {
        mHandler.removeCallbacks(task);
    }

    public static String[] getStringArray(int resId) {
        return mBaseContext.getResources().getStringArray(resId);
    }

    // 获取资源文件夹
    public static Resources getResources() {
        return mBaseContext.getResources();
    }

    // 获取资源文件夹的字符串
    public static String getString(int id, Object... formatArgs) {
        return getResources().getString(id, formatArgs);
    }


    public static String getDateHHmm(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("HH:mm");
        Date d = new Date(time);
        return sf.format(d);
    }

    public static String getTime(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date d = new Date(time);
        return sf.format(d);
    }

    public static String get2Time(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Date d = new Date(time);
        return sf.format(d);
    }

    public static String get3Time(long time) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        Date d = new Date(time);
        return sf.format(d);
    }

    public static int getScreenHeight(Activity activity) {
        return activity.getWindowManager()
                .getDefaultDisplay().getHeight();
    }

    public static int getScreenWidth(Activity activity) {
        return activity.getWindowManager()
                .getDefaultDisplay().getWidth();
    }

    public static void getPwdStyle(CharSequence s, int start, int before, EditText editText) {
        if (s == null || s.length() == 0) return;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (i != 3 && i != 8 && s.charAt(i) == ' ') {
                continue;
            } else {
                sb.append(s.charAt(i));
                if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != ' ') {
                    sb.insert(sb.length() - 1, ' ');
                }
            }
        }
        if (!sb.toString().equals(s.toString())) {
            int index = start + 1;
            if (sb.charAt(start) == ' ') {
                if (before == 0) {
                    index++;
                } else {
                    index--;
                }
            } else {
                if (before == 1) {
                    index--;
                }
            }
            editText.setText(sb.toString());
            editText.setSelection(index);
        }
    }

    /**
     * dp --> px
     *
     * @param dp
     * @return
     */
    public static float dp2px(float dp) {
        float dimension = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_PX,
                dp,
                getResources().getDisplayMetrics());
        return dimension;
    }

    // 将px转换为dp
    public static float px2dp(float px) {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                px,
                getResources().getDisplayMetrics());
    }


    public static int getColor(int colorId) {
        return getResources().getColor(colorId);
    }


    /**
     * 压缩图片（质量压缩）
     *
     * @param bitmap
     */
    public static File compressImage(Bitmap bitmap, String path) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
        int options = 100;
        while (baos.toByteArray().length / 1024 > 500) {
            baos.reset();
            options -= 10;
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);
            long length = baos.toByteArray().length;
        }
        //  File file = new File(Constants.CAPTURED_FRAME_FILE_PATH + path);
        try {
            //   FileOutputStream fos = new FileOutputStream(file);
            FileOutputStream fos = new FileOutputStream(new File(""));
            try {
                fos.write(baos.toByteArray());
                fos.flush();
                fos.close();
            } catch (IOException e) {

                System.out.println("异常信息1==" + e.toString());
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            System.out.println("异常信息2==" + e.toString());
            e.printStackTrace();
        }
        //return file;
        return null;
    }


    public static void destroyBitmap(Bitmap bitmap) {
        if (bitmap == null) return;
        if (!bitmap.isRecycled())
            bitmap.recycle();
        bitmap = null;
    }

    public static void recycleBitmap(Bitmap... bitmaps) {
        if (bitmaps == null) {
            return;
        }
        for (Bitmap bm : bitmaps) {
            if (null != bm && !bm.isRecycled()) {
                bm.recycle();
            }
        }
    }

    public static void deleteFiles(File file) {
        if (file != null && file.exists() && file.isDirectory()) {
            for (File item : file.listFiles()) {
                item.delete();
            }
        }
    }


    //将bitmap调整到指定大小
    public static Bitmap sizeBitmap(Bitmap origin, int newWidth, int newHeight) {
        if (origin == null) {
            return null;
        }
        int height = origin.getHeight();
        int width = origin.getWidth();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);// 使用后乘
        Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);
        if (!origin.isRecycled()) {//这时候origin还有吗？
            origin.recycle();
        }
        return newBM;
    }

    /**
     * 手机号码的格式183-2964-611
     *
     * @param s
     * @param start
     * @param before
     * @param et_01
     */
    private static void getPhoneStyle(CharSequence s, int start, int before, EditText et_01) {
        if (s == null || s.length() == 0) return;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (i != 3 && i != 8 && s.charAt(i) == '-') {
                continue;
            } else {
                sb.append(s.charAt(i));
                if ((sb.length() == 4 || sb.length() == 9) && sb.charAt(sb.length() - 1) != '-') {
                    sb.insert(sb.length() - 1, '-');
                }
            }
        }
        if (!sb.toString().equals(s.toString())) {
            int index = start + 1;
            if (sb.charAt(start) == '-') {
                if (before == 0) {
                    index++;
                } else {
                    index--;
                }
            } else {
                if (before == 1) {
                    index--;
                }
            }
            et_01.setText(sb.toString());
            et_01.setSelection(index);
        }
    }


    /**
     * 获取深色外的随机颜色
     *
     * @return
     */
    public static int getRandomColor() {
        return 0xff000000 | new Random().nextInt(0x00ffffff);
    }


    public static int dip2px(Context context, float dipValue) {
        if (context == null) {
            return (int) dipValue;
        }
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }


    /**
     * 大陆号码或香港号码均可
     */
    public static boolean isPhoneLegal(String str) throws PatternSyntaxException {
        return isChinaPhoneLegal(str) || isHKPhoneLegal(str);
    }

    /**
     * 大陆手机号码11位数，匹配格式：前三位固定格式+后8位任意数
     * 此方法中前三位格式有：
     * 13+任意数
     * 15+除4的任意数
     * 18+除1和4的任意数
     * 17+除9的任意数
     * 147
     */
    public static boolean isChinaPhoneLegal(String str) throws PatternSyntaxException {
        String regExp = "^((13[0-9])|(15[^4])|(18[0,2,3,5-9])|(17[0-8])|(147))\\d{8}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }

    /**
     * 香港手机号码8位数，5|6|8|9开头+7位任意数
     */
    public static boolean isHKPhoneLegal(String str) throws PatternSyntaxException {
        String regExp = "^(5|6|8|9)\\d{7}$";
        Pattern p = Pattern.compile(regExp);
        Matcher m = p.matcher(str);
        return m.matches();
    }


    /**
     * 加密
     *
     * @param datasource byte[]
     * @param password   String
     * @return byte[]
     */
    public static byte[] encrypt(byte[] datasource, String password) {
        try {
            SecureRandom random = new SecureRandom();
            DESKeySpec desKey = new DESKeySpec(password.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey securekey = keyFactory.generateSecret(desKey);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, securekey, random);
            return cipher.doFinal(datasource);
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 解密
     *
     * @param src      byte[]
     * @param password String
     * @return byte[]
     */
    public static byte[] decrypt(byte[] src, String password) throws Exception {
        SecureRandom random = new SecureRandom();
        DESKeySpec desKey = new DESKeySpec(password.getBytes());
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey securekey = keyFactory.generateSecret(desKey);
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, securekey, random);
        return cipher.doFinal(src);
    }


    /**
     * 限制只能输入小数点后两位
     *
     * @param editText
     * @param s
     */
    public static void InputTwo(EditText editText, CharSequence s) {
        if (s.toString().contains(".")) {
            if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                s = s.toString().subSequence(0,
                        s.toString().indexOf(".") + 3);
                editText.setText(s);
                editText.setSelection(s.length());
            }
        }
        if (s.toString().trim().substring(0).equals(".")) {
            s = "0" + s;
            editText.setText(s);
            editText.setSelection(2);
        }
        if (s.toString().startsWith("0")
                && s.toString().trim().length() > 1) {
            if (!s.toString().substring(1, 2).equals(".")) {
                editText.setText(s.subSequence(0, 1));
                editText.setSelection(1);
                return;
            }
        }
    }


    public static String getDecimalFormat(double num) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(num);
    }

    public static String getDecimalFormat(float num) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(num);
    }

    public static String getDecimalFormat(String num) {
        DecimalFormat df = new DecimalFormat("0.00");
        return df.format(num);
    }

    public static String getMonthOfDate() {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        Date theDate = calendar.getTime();
        GregorianCalendar gcLast = (GregorianCalendar) Calendar.getInstance();
        gcLast.setTime(theDate);
        gcLast.set(Calendar.DAY_OF_MONTH, 1);
        return sf.format(gcLast.getTime());
    }


    public static String getMon() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Calendar c = Calendar.getInstance();
        c.setTime(new Date());
        c.add(Calendar.MONTH, -1);
        Date m = c.getTime();
        String mon = format.format(m);
        return mon;
    }


    private static void dealPattern(int color, SpannableString spannableString, Pattern patten, int start) throws Exception {
        Matcher matcher = patten.matcher(spannableString);
        while (matcher.find()) {
            String key = matcher.group();
            // 返回第一个字符的索引的文本匹配整个正则表达式,ture 则继续递归
            if (matcher.start() < start) {
                continue;
            }
            // 计算该内容的长度，也就是要替换的字符串的长度
            int end = matcher.start() + key.length();
            //设置前景色span
            spannableString.setSpan(new ForegroundColorSpan(color), matcher.start(), end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            if (end < spannableString.length()) {
                // 如果整个字符串还未验证完，则继续。。
                dealPattern(color, spannableString, patten, end);
            }
            break;
        }
    }

    public static String getJson(String fileName, Context context) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = context.getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(fileName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return stringBuilder.toString();
    }


    /**
     * 关键字变色
     *
     * @param color
     * @param str
     * @param patterStr
     * @return
     */
    public static SpannableString getKeyWordSpan(int color, String str, String patterStr) {
        SpannableString spannableString = new SpannableString(str);
        try {
            Pattern patten = Pattern.compile(patterStr, Pattern.CASE_INSENSITIVE);
            dealPattern(color, spannableString, patten, 0);
            return spannableString;
        } catch (Exception e) {
            return spannableString;
        }
    }


    /**
     * 弹出Toast
     *
     * @param msg
     */
    public static void showToast(String msg) {
        Toast.makeText(UiUtil.getContext(), msg, Toast.LENGTH_SHORT).show();
    }


    /**
     * 发送消息
     *
     * @param code
     * @param data
     */
    public static void sendMsg(int code, Object data) {
        MessageEvent instance = new MessageEvent();
        instance.data = data;
        instance.code = code;
        EventBus.getDefault().post(instance);
    }


    /**
     * 隐藏软键盘
     *
     * @param activity
     */
    public static void hide(Activity activity) {
        if (activity.getCurrentFocus() != null) {
            InputMethodManager imm = (InputMethodManager) activity
                    .getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
        }
    }

    /**
     * 显示软键盘
     *
     * @param activity
     */
    public static void show(Activity activity) {
        View view = activity.getWindow().peekDecorView();
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }


    /**
     * 把十六进制Unicode编码字符串转换为中文字符串
     *
     * @param str
     * @return
     */
    public static String unicodeToString(String str) {
        Pattern pattern = Pattern.compile("(\\\\u(\\p{XDigit}{2,4}))");
        Matcher matcher = pattern.matcher(str);
        char ch;
        while (matcher.find()) {
            ch = (char) Integer.parseInt(matcher.group(2), 16);
            str = str.replace(matcher.group(1), ch + "");
        }
        return str;
    }


    public static String getConstellation(int month, int day) {
        String constellation = "白羊座";
        switch (month) {
            case 1:
                if (day < 22) constellation = "摩羯座";
                else constellation = "水瓶座";
                break;
            case 2:
                if (day < 22) constellation = "水瓶座";
                else constellation = "双鱼座";
                break;
            case 3:
                if (day < 22) constellation = "双鱼座";
                else constellation = "白羊座";
                break;
            case 4:
                if (day < 22) constellation = "白羊座";
                else constellation = "金牛座";
                break;
            case 5:
                if (day < 22) constellation = "金牛座";
                else constellation = "双子座";
                break;
            case 6:
                if (day < 22) constellation = "双子座";
                else constellation = "巨蟹座";
                break;
            case 7:
                if (day < 22) constellation = "巨蟹座";
                else constellation = "狮子座";
                break;
            case 8:
                if (day < 22) constellation = "狮子座";
                else constellation = "处女座";
                break;
            case 9:
                if (day < 22) constellation = "处女座";
                else constellation = "天枰座";
                break;
            case 10:
                if (day < 22) constellation = "天枰座";
                else constellation = "天蝎座";
                break;
            case 11:
                if (day < 22) constellation = "天蝎座";
                else constellation = "射手座";
                break;
            case 12:
                if (day < 22) constellation = "射手座";
                else constellation = "摩羯座";
                break;
        }
        return constellation;
    }


    public static boolean slideHide(int dy, boolean isFirst, View view, int s) {
        if (dy != 0 && Math.abs(dy) > 5) {
            if (dy > 0 && Math.abs(dy) >= 20) {
                if (isFirst && s == 2) {
                    view.animate().translationY(view.getHeight() * 2);
                    isFirst = !isFirst;
                }
                return isFirst;
            } else {
                view.setVisibility(View.VISIBLE);
                if (Math.abs(dy) >= 20)
                    if (!isFirst && s == 2) {
                        view.animate().translationY(0);
                        isFirst = !isFirst;
                    }
            }
            return isFirst;
        }
        return isFirst;
    }

    public static void isChartPathExist(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists()) {
            file.mkdirs();
        } else {
            System.out.println("存在删除");
            String[] tempList = file.list();
            File temp;
            for (int i = 0; i < tempList.length; i++) {
                if (dirPath.endsWith(File.separator)) {
                    temp = new File(dirPath + tempList[i]);
                } else {
                    temp = new File(dirPath + File.separator + tempList[i]);
                }
                if (temp.isFile()) {
                    temp.delete();
                }
            }
        }
    }

    /**
     * @param bmp     获取的bitmap数据
     * @param picName 自定义的图片名
     */
    public static void saveBmp2Gallery(Bitmap bmp, String picName) {

        String fileName = null;
        //系统相册目录
        String galleryPath = Environment.getExternalStorageDirectory()
                + File.separator + Environment.DIRECTORY_DCIM
                + File.separator + "Camera" + File.separator;
        // 声明文件对象
        File file = null;
        // 声明输出流
        FileOutputStream outStream = null;

        try {
            // 如果有目标文件，直接获得文件对象，否则创建一个以filename为名称的文件
            file = new File(galleryPath, picName + ".jpg");

            // 获得文件相对路径
            fileName = file.toString();
            // 获得输出流，如果文件中有内容，追加内容
            outStream = new FileOutputStream(fileName);
            if (null != outStream) {
                bmp.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
            }

        } catch (Exception e) {
            e.getStackTrace();
        } finally {
            try {
                if (outStream != null) {
                    outStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        //通知相册更新
        MediaStore.Images.Media.insertImage(UiUtil.getContext().getContentResolver(),
                bmp, fileName, null);
        Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        Uri uri = Uri.fromFile(file);
        intent.setData(uri);
        UiUtil.getContext().sendBroadcast(intent);
        UiUtil.showToast("保存成功!");
    }


    public static String getVersions() {
        PackageManager manager = UiUtil.getContext().getPackageManager();
        String name = null;
        try {
            PackageInfo info = manager.getPackageInfo(UiUtil.getContext().getPackageName(), 0);
            name = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return name;
    }


    public static Date parse(String strDate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.parse(strDate);
    }

    //由出生日期获得年龄
    public static int getAge(Date birthDay) throws Exception {
        Calendar cal = Calendar.getInstance();
        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            } else {
                age--;
            }
        }
        return age;
    }


    public static String getName() {
        Random random = new Random();
        String[] Surname = {"赵", "钱", "孙", "李", "周", "吴", "郑", "王", "冯", "陈", "褚", "卫", "蒋", "沈", "韩", "杨", "朱", "秦", "尤", "许",
                "何", "吕", "施", "张", "孔", "曹", "严", "华", "金", "魏", "陶", "姜", "戚", "谢", "邹", "喻", "柏", "水", "窦", "章", "云", "苏", "潘", "葛", "奚", "范", "彭", "郎",
                "鲁", "韦", "昌", "马", "苗", "凤", "花", "方", "俞", "任", "袁", "柳", "酆", "鲍", "史", "唐", "费", "廉", "岑", "薛", "雷", "贺", "倪", "汤", "滕", "殷",
                "罗", "毕", "郝", "邬", "安", "常", "乐", "于", "时", "傅", "皮", "卞", "齐", "康", "伍", "余", "元", "卜", "顾", "孟", "平", "黄", "和",
                "穆", "萧", "尹", "姚", "邵", "湛", "汪", "祁", "毛", "禹", "狄", "米", "贝", "明", "臧", "计", "伏", "成", "戴", "谈", "宋", "茅", "庞", "熊", "纪", "舒",
                "屈", "项", "祝", "董", "梁", "杜", "阮", "蓝", "闵", "席", "季"};
        String girl = "秀娟英华慧巧美娜静淑惠珠翠雅芝玉萍红娥玲芬芳燕彩春菊兰凤洁梅琳素云莲真环雪荣爱妹霞香月莺媛艳瑞凡佳嘉琼勤珍贞莉桂娣叶璧璐娅琦晶妍茜秋珊莎锦黛青倩婷姣婉娴瑾颖露瑶怡婵雁蓓纨仪荷丹蓉眉君琴蕊薇菁梦岚苑婕馨瑗琰韵融园艺咏卿聪澜纯毓悦昭冰爽琬茗羽希宁欣飘育滢馥筠柔竹霭凝晓欢霄枫芸菲寒伊亚宜可姬舒影荔枝思丽 ";
        String boy = "伟刚勇毅俊峰强军平保东文辉力明永健世广志义兴良海山仁波宁贵福生龙元全国胜学祥才发武新利清飞彬富顺信子杰涛昌成康星光天达安岩中茂进林有坚和彪博诚先敬震振壮会思群豪心邦承乐绍功松善厚庆磊民友裕河哲江超浩亮政谦亨奇固之轮翰朗伯宏言若鸣朋斌梁栋维启克伦翔旭鹏泽晨辰士以建家致树炎德行时泰盛雄琛钧冠策腾楠榕风航弘";
        int index = random.nextInt(Surname.length - 1);
        String name = Surname[index]; //获得一个随机的姓氏
        int i = random.nextInt(3);//可以根据这个数设置产生的男女比例
        if (i == 2) {
            int j = random.nextInt(girl.length() - 2);
            if (j % 2 == 0) {
                // name = "女-" + name + girl.substring(j, j + 2);
                name = name + girl.substring(j, j + 2);
            } else {
                name = name + girl.substring(j, j + 1);
            }

        } else {
            int j = random.nextInt(girl.length() - 2);
            if (j % 2 == 0) {
                // name = "男-" + name + boy.substring(j, j + 2);
                name = name + boy.substring(j, j + 2);
            } else {
                name = name + boy.substring(j, j + 1);
            }

        }

        return name;
    }


    public static Bitmap getVideoThumb(String path, int radius) {
        Bitmap bitmap = null;
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(path);
        bitmap = media.getFrameAtTime();
        Bitmap blurBitmap = doBlur(bitmap, radius, false);
        bitmap.recycle();
        return blurBitmap;
    }

    public static Bitmap getBlur(Bitmap bitmap) {
        Bitmap blurBitmap = doBlur(bitmap, 10, false);
        bitmap.recycle();
        return blurBitmap;
    }

    public static Bitmap getThumbFrame(String path) {
        Bitmap bitmap = null;
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(path);
        bitmap = media.getFrameAtTime();
        return bitmap;
    }

    public static Bitmap getThumbLocalFrame(String path) {
        MediaMetadataRetriever media = new MediaMetadataRetriever();
        media.setDataSource(path);// videoPath 本地视频的路径
        Bitmap bitmap = media.getFrameAtTime(1, MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
        return bitmap;
    }


    private static String getSortkey(String sortKeyString) {
        String key = sortKeyString.substring(0, 1).toUpperCase();
        if (key.matches("[A-Z]")) {
            return key;
        } else
            return "#";
    }


    public static View showPop(Activity activity, int layoutRes) {
        View pop_special = View.inflate(UiUtil.getContext(), layoutRes, null);
        mPopupWindow = new PopupWindow(pop_special, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        mPopupWindow.setFocusable(true);
        setBackgroundAlpha(0.5f, activity);
        mPopupWindow.setOnDismissListener(() -> setBackgroundAlpha(1.0f, activity));
        mPopupWindow.setBackgroundDrawable(new ColorDrawable());
        mPopupWindow.showAtLocation(activity.getWindow().getDecorView(), Gravity.CENTER, 0, 0);
        return pop_special;
    }

    public static void setBackgroundAlpha(float bgAlpha, Activity activity) {
        WindowManager.LayoutParams lp = activity.getWindow()
                .getAttributes();
        lp.alpha = bgAlpha;
        activity.getWindow().setAttributes(lp);
    }

    public static String bytes2kb(long bytes) {
        BigDecimal filesize = new BigDecimal(bytes);
        BigDecimal megabyte = new BigDecimal(1024 * 1024);
        float returnValue = filesize.divide(megabyte, 2, BigDecimal.ROUND_UP)
                .floatValue();
        if (returnValue > 1)
            return (returnValue + "MB");
        BigDecimal kilobyte = new BigDecimal(1024);
        returnValue = filesize.divide(kilobyte, 2, BigDecimal.ROUND_UP)
                .floatValue();
        return (returnValue + "KB");
    }


    public static Bitmap getNetVideoBitmap(String videoUrl) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();
        try {
            //根据url获取缩略图
            retriever.setDataSource(videoUrl, new HashMap());
            //获得第一帧图片
            bitmap = retriever.getFrameAtTime();
            Bitmap blurBitmap = doBlur(bitmap, 10, false);
            bitmap.recycle();
            return blurBitmap;
        } catch (IllegalArgumentException e) {
            System.out.println("出错");
            e.printStackTrace();
        } finally {
            retriever.release();
        }
        return bitmap;
    }


    public static Bitmap doBlur(Bitmap sentBitmap, int radius, boolean canReuseInBitmap) {

        Bitmap bitmap;
        if (canReuseInBitmap) {
            bitmap = sentBitmap;
        } else {
            bitmap = sentBitmap.copy(sentBitmap.getConfig(), true);
        }

        if (radius < 1) {
            return (null);
        }

        int w = bitmap.getWidth();
        int h = bitmap.getHeight();

        int[] pix = new int[w * h];
        bitmap.getPixels(pix, 0, w, 0, 0, w, h);

        int wm = w - 1;
        int hm = h - 1;
        int wh = w * h;
        int div = radius + radius + 1;

        int r[] = new int[wh];
        int g[] = new int[wh];
        int b[] = new int[wh];
        int rsum, gsum, bsum, x, y, i, p, yp, yi, yw;
        int vmin[] = new int[Math.max(w, h)];

        int divsum = (div + 1) >> 1;
        divsum *= divsum;
        int dv[] = new int[256 * divsum];
        for (i = 0; i < 256 * divsum; i++) {
            dv[i] = (i / divsum);
        }

        yw = yi = 0;

        int[][] stack = new int[div][3];
        int stackpointer;
        int stackstart;
        int[] sir;
        int rbs;
        int r1 = radius + 1;
        int routsum, goutsum, boutsum;
        int rinsum, ginsum, binsum;

        for (y = 0; y < h; y++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            for (i = -radius; i <= radius; i++) {
                p = pix[yi + Math.min(wm, Math.max(i, 0))];
                sir = stack[i + radius];
                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);
                rbs = r1 - Math.abs(i);
                rsum += sir[0] * rbs;
                gsum += sir[1] * rbs;
                bsum += sir[2] * rbs;
                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }
            }
            stackpointer = radius;

            for (x = 0; x < w; x++) {

                r[yi] = dv[rsum];
                g[yi] = dv[gsum];
                b[yi] = dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (y == 0) {
                    vmin[x] = Math.min(x + radius + 1, wm);
                }
                p = pix[yw + vmin[x]];

                sir[0] = (p & 0xff0000) >> 16;
                sir[1] = (p & 0x00ff00) >> 8;
                sir[2] = (p & 0x0000ff);

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[(stackpointer) % div];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi++;
            }
            yw += w;
        }
        for (x = 0; x < w; x++) {
            rinsum = ginsum = binsum = routsum = goutsum = boutsum = rsum = gsum = bsum = 0;
            yp = -radius * w;
            for (i = -radius; i <= radius; i++) {
                yi = Math.max(0, yp) + x;

                sir = stack[i + radius];

                sir[0] = r[yi];
                sir[1] = g[yi];
                sir[2] = b[yi];

                rbs = r1 - Math.abs(i);

                rsum += r[yi] * rbs;
                gsum += g[yi] * rbs;
                bsum += b[yi] * rbs;

                if (i > 0) {
                    rinsum += sir[0];
                    ginsum += sir[1];
                    binsum += sir[2];
                } else {
                    routsum += sir[0];
                    goutsum += sir[1];
                    boutsum += sir[2];
                }

                if (i < hm) {
                    yp += w;
                }
            }
            yi = x;
            stackpointer = radius;
            for (y = 0; y < h; y++) {
                // Preserve alpha channel: ( 0xff000000 & pix[yi] )
                pix[yi] = (0xff000000 & pix[yi]) | (dv[rsum] << 16) | (dv[gsum] << 8) | dv[bsum];

                rsum -= routsum;
                gsum -= goutsum;
                bsum -= boutsum;

                stackstart = stackpointer - radius + div;
                sir = stack[stackstart % div];

                routsum -= sir[0];
                goutsum -= sir[1];
                boutsum -= sir[2];

                if (x == 0) {
                    vmin[y] = Math.min(y + r1, hm) * w;
                }
                p = x + vmin[y];

                sir[0] = r[p];
                sir[1] = g[p];
                sir[2] = b[p];

                rinsum += sir[0];
                ginsum += sir[1];
                binsum += sir[2];

                rsum += rinsum;
                gsum += ginsum;
                bsum += binsum;

                stackpointer = (stackpointer + 1) % div;
                sir = stack[stackpointer];

                routsum += sir[0];
                goutsum += sir[1];
                boutsum += sir[2];

                rinsum -= sir[0];
                ginsum -= sir[1];
                binsum -= sir[2];

                yi += w;
            }
        }

        bitmap.setPixels(pix, 0, w, 0, 0, w, h);

//        print("虚化后 ",bitmap);
        return (bitmap);
    }


    public static Date strToDateLong(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }


    public static String rvZeroAndDot(String s) {
        if (s.isEmpty()) {
            return null;
        }
        if (s.indexOf(".") > 0) {
            s = s.replaceAll("0+?$", "");//去掉多余的0
            s = s.replaceAll("[.]$", "");//如最后一位是.则去掉
        }
        return s;
    }


    public static double getDistance(double longitude1, double latitude1,
                                     double longitude2, double latitude2) {
        double Lat1 = rad(latitude1);
        double Lat2 = rad(latitude2);
        double a = Lat1 - Lat2;
        double b = rad(longitude1) - rad(longitude2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(Lat1) * Math.cos(Lat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378137;
        s = Math.round(s * 10000) / 10000;
        return s;
    }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }


    @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
    public static Bitmap blurBitmap(Context context, Bitmap image, float blurRadius, int outWidth, int outHeight) {
        // 将缩小后的图片做为预渲染的图片
        Bitmap inputBitmap = Bitmap.createScaledBitmap(image, outWidth, outHeight, false);
        // 创建一张渲染后的输出图片
        Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
        // 创建RenderScript内核对象
        RenderScript rs = RenderScript.create(context);
        // 创建一个模糊效果的RenderScript的工具对象
        ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        // 由于RenderScript并没有使用VM来分配内存,所以需要使用Allocation类来创建和分配内存空间
        // 创建Allocation对象的时候其实内存是空的,需要使用copyTo()将数据填充进去
        Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
        Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
        // 设置渲染的模糊程度, 25f是最大模糊度
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            blurScript.setRadius(blurRadius);
        }
        // 设置blurScript对象的输入内存
        blurScript.setInput(tmpIn);
        // 将输出数据保存到输出内存中
        blurScript.forEach(tmpOut);
        // 将数据填充到Allocation中
        tmpOut.copyTo(outputBitmap);
        return outputBitmap;
    }


    /**
     * 取得文件大小
     *
     * @param f
     * @return
     * @throws Exception
     */
    public static long getFileSizes(File f) throws Exception {
        long s = 0;
        if (f.exists()) {
            FileInputStream fis = null;
            fis = new FileInputStream(f);
            s = fis.available();
        } else {
            f.createNewFile();
        }
        return s;
    }

    /**
     * 转换文件大小
     *
     * @param fileS
     * @return
     */
    public static String FormetFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + "K";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + "G";
        }
        return fileSizeString;
    }


    public static String stringFilter(String str) throws PatternSyntaxException {
        // 只允许字母、数字和汉字其余的还可以随时添加比如下划线什么的，但是注意引文符号和中文符号区别
        String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";//正则表达式
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public static void setEtFilter(EditText et) {
        if (et == null) {
            return;
        }
        //表情过滤器
        InputFilter emojiFilter = (source, start, end, dest, dstart, dend) -> {
            Pattern emoji = Pattern.compile(
                    "[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                    Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
            Matcher emojiMatcher = emoji.matcher(source);
            if (emojiMatcher.find()) {
                return "";
            }
            return null;
        };
        //特殊字符过滤器
        InputFilter specialCharFilter = (source, start, end, dest, dstart, dend) -> {
            String regexStr = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
            Pattern pattern = Pattern.compile(regexStr);
            Matcher matcher = pattern.matcher(source.toString());
            if (matcher.matches()) {
                return "";
            } else {
                return null;
            }

        };
        et.setFilters(new InputFilter[]{emojiFilter, specialCharFilter});
    }

    public static void setEtFilter(EditText et, int maxLength) {
        if (et == null) {
            return;
        }
        //表情过滤器
        InputFilter emojiFilter = (source, start, end, dest, dstart, dend) -> {
            Pattern emoji = Pattern.compile(
                    "[\ud83c\udc00-\ud83c\udfff]|[\ud83d\udc00-\ud83d\udfff]|[\u2600-\u27ff]",
                    Pattern.UNICODE_CASE | Pattern.CASE_INSENSITIVE);
            Matcher emojiMatcher = emoji.matcher(source);
            if (emojiMatcher.find()) {
                return "";
            }
            return null;
        };
        //特殊字符过滤器
        InputFilter specialCharFilter = (source, start, end, dest, dstart, dend) -> {
            String regexStr = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
            Pattern pattern = Pattern.compile(regexStr);
            Matcher matcher = pattern.matcher(source.toString());
            if (matcher.matches()) {
                return "";
            } else {
                return null;
            }

        };
        et.setFilters(new InputFilter[]{emojiFilter, specialCharFilter, new InputFilter.LengthFilter(maxLength)});
    }


    public static String getMobileFormat(String theMobileStr) {
        return theMobileStr.substring(0, 3) + " " + theMobileStr.substring(3, 7) + " " + theMobileStr.substring(7);
    }


    /**
     * 获取Glide造成的缓存大小
     *
     * @return CacheSize
     */
    public static String getCacheSize(Context context) {
        try {
            return getFormatSize(getFolderSize(new File(context.getCacheDir() + "/" + InternalCacheDiskCacheFactory.DEFAULT_DISK_CACHE_DIR)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }


    /**
     * 获取指定文件夹内所有文件大小的和
     *
     * @param file file
     * @return size
     * @throws Exception
     */
    private static long getFolderSize(File file) throws Exception {
        long size = 0;
        try {
            File[] fileList = file.listFiles();
            for (File aFileList : fileList) {
                if (aFileList.isDirectory()) {
                    size = size + getFolderSize(aFileList);
                } else {
                    size = size + aFileList.length();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;

    }


    private static String getFormatSize(double size) {

        double kiloByte = size / 1024;
        if (kiloByte < 1) {
            return size + "Byte";
        }

        double megaByte = kiloByte / 1024;
        if (megaByte < 1) {
            BigDecimal result1 = new BigDecimal(Double.toString(kiloByte));
            return result1.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "KB";
        }

        double gigaByte = megaByte / 1024;
        if (gigaByte < 1) {
            BigDecimal result2 = new BigDecimal(Double.toString(megaByte));
            return result2.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "MB";
        }

        double teraBytes = gigaByte / 1024;
        if (teraBytes < 1) {
            BigDecimal result3 = new BigDecimal(Double.toString(gigaByte));
            return result3.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "GB";
        }
        BigDecimal result4 = new BigDecimal(teraBytes);

        return result4.setScale(2, BigDecimal.ROUND_HALF_UP).toPlainString() + "TB";
    }


    public static void clearImageDiskCache(Context context) {
        try {
            if (Looper.myLooper() == Looper.getMainLooper()) {
                new Thread(() -> Glide.get(context).clearDiskCache()).start();
            } else {
                Glide.get(context).clearDiskCache();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 设置提示字体的大小
     *
     * @param editText 你使用的EditText
     */
    public static void setEditTextHintSize(EditText editText) {
        SpannableString ss = new SpannableString("请输入手机号码");
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(20, true);
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        editText.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
    }


    public static boolean CheckMobilePhoneNum(String phoneNum) {
        String regex = "^(1[3-9]\\d{9}$)";
        if (phoneNum.length() == 11) {
            Pattern p = Pattern.compile(regex);
            Matcher m = p.matcher(phoneNum);
            if (m.matches()) {
                return true;
            }
        }
        return false;
    }


    public static String unicodeToCn(String unicode) {
        /** 以 \ u 分割，因为java注释也能识别unicode，因此中间加了一个空格*/
        String[] strs = unicode.split("\\\\u");
        String returnStr = "";
        // 由于unicode字符串以 \ u 开头，因此分割出的第一个字符是""。
        for (int i = 1; i < strs.length; i++) {
            returnStr += (char) Integer.valueOf(strs[i], 16).intValue();
        }
        return returnStr;
    }


    public static boolean check(String str) {
        SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd");//括号内为日期格式，y代表年份，M代表年份中的月份（为避免与小时中的分钟数m冲突，此处用M），d代表月份中的天数
        try {
            sd.setLenient(false);//此处指定日期/时间解析是否不严格，在true是不严格，false时为严格
            sd.parse(str);//从给定字符串的开始解析文本，以生成一个日期
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    public static Date strToDate(String strDate) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        ParsePosition pos = new ParsePosition(0);
        Date strtodate = formatter.parse(strDate, pos);
        return strtodate;
    }


    public static boolean checkAdult(Date date) {

        Calendar current = Calendar.getInstance();
        Calendar birthDay = Calendar.getInstance();
        birthDay.setTime(date);
        Integer year = current.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
        if (year > 18) {
            return true;
        } else if (year < 18) {
            return false;
        }
        // 如果年相等，就比较月份
        Integer month = current.get(Calendar.MONTH) - birthDay.get(Calendar.MONTH);
        if (month > 0) {
            return true;
        } else if (month < 0) {
            return false;
        }
        // 如果月也相等，就比较天
        Integer day = current.get(Calendar.DAY_OF_MONTH) - birthDay.get(Calendar.DAY_OF_MONTH);
        return day >= 0;
    }


    public static String getOnlineTime(String onlineTimeStr) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = simpleDateFormat.parse(onlineTimeStr);
            Date dateNow = new Date();

            long timeLong = (dateNow.getTime() / 1000 - date.getTime() / 1000);
            if (timeLong <= 60) {
                return "活跃";
            } else if (timeLong > 60 && timeLong < 60 * 60) {
                int minute = (int) (timeLong / 60);

                return minute + "分钟前活跃";
            } else if (timeLong > 60 * 60 && timeLong < 60 * 60 * 24) {
                int hour = (int) (timeLong / (60 * 60));

                return hour + "小时前活跃";
            } else if (timeLong > 60 * 60 * 24 && timeLong < 60 * 60 * 24 * 30) {
                int day = (int) (timeLong / (60 * 60 * 24));

                return day + "天前活跃";
            } else if (timeLong > 60 * 60 * 24 * 30 && timeLong < 60 * 60 * 24 * 30 * 12) {
                int month = (int) (timeLong / (60 * 60 * 24 * 30));

                return month + "个月前活跃";
            } else if (timeLong > 60 * 60 * 24 * 30 * 12) {
                int year = (int) (timeLong / (60 * 60 * 24 * 30 * 12));

                return year + "年前活跃";
            } else {
                return onlineTimeStr;
            }

        } catch (ParseException e) {
            e.printStackTrace();

            return onlineTimeStr;

        }


    }

    public static String get2OnlineTime(String onlineTimeStr) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date date = simpleDateFormat.parse(onlineTimeStr);
            Date dateNow = new Date();

            long timeLong = (dateNow.getTime() / 1000 - date.getTime() / 1000);
            if (timeLong <= 60) {
                return "活跃";
            } else if (timeLong > 60 && timeLong < 60 * 60) {
                int minute = (int) (timeLong / 60);

                return minute + "分钟前活跃";
            } else if (timeLong > 60 * 60 && timeLong < 60 * 60 * 24) {
                int hour = (int) (timeLong / (60 * 60));

                return hour + "小时前活跃";
            } else if (timeLong > 60 * 60 * 24 && timeLong < 60 * 60 * 24 * 30) {
                int day = (int) (timeLong / (60 * 60 * 24));

                return day + "天前活跃";
            } else if (timeLong > 60 * 60 * 24 * 30 && timeLong < 60 * 60 * 24 * 30 * 12) {
                int month = (int) (timeLong / (60 * 60 * 24 * 30));

                return month + "个月前活跃";
            } else if (timeLong > 60 * 60 * 24 * 30 * 12) {
                int year = (int) (timeLong / (60 * 60 * 24 * 30 * 12));

                return year + "年前活跃";
            } else {
                return onlineTimeStr;
            }

        } catch (ParseException e) {
            e.printStackTrace();

            return onlineTimeStr;

        }


    }


    /**
     * 格式化时间
     *
     * @param time
     * @return
     */
    public static String formatDateTime(String time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if (time == null || "".equals(time)) {
            return "";
        }
        Date date = null;
        try {
            date = format.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        Calendar current = Calendar.getInstance();

        Calendar today = Calendar.getInstance();    //今天

        today.set(Calendar.YEAR, current.get(Calendar.YEAR));
        today.set(Calendar.MONTH, current.get(Calendar.MONTH));
        today.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH) - 1);
        today.set(Calendar.HOUR_OF_DAY, 0);
        today.set(Calendar.MINUTE, 0);
        today.set(Calendar.SECOND, 0);
        Calendar yesterday = Calendar.getInstance();    //昨天
        yesterday.set(Calendar.YEAR, current.get(Calendar.YEAR));
        yesterday.set(Calendar.MONTH, current.get(Calendar.MONTH));
        yesterday.set(Calendar.DAY_OF_MONTH, current.get(Calendar.DAY_OF_MONTH) - 2);
        yesterday.set(Calendar.HOUR_OF_DAY, 0);
        yesterday.set(Calendar.MINUTE, 0);
        yesterday.set(Calendar.SECOND, 0);
        current.setTime(date);
        if (current.after(today)) {
            return "今天";
        } else if (current.before(today) && current.after(yesterday)) {
            return "昨天";
        } else {
            return time;
        }
    }


    public static Date getDate(String time) {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date dateTime = null;
        try {
            dateTime = simpleDateFormat.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return dateTime;
    }

    // 当前时间7天后的时间
    public static String getTimeDay(String time) {
        Date date = getDate(time);
        String lastModified = new SimpleDateFormat("yyyy-MM-dd").format(new Date((date.getTime() + (long) 7 * 24 * 60 * 60 * 1000)));
        return lastModified;
    }


    /**
     * date2比date1多的天数
     *
     * @param date1
     * @param date2
     * @return
     */
    public static int differentDays(Date date1, Date date2) {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);
        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1 = cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if (year1 != year2) {
            //同一年
            int timeDistance = 0;
            for (int i = year1; i < year2; i++) {
                if (i % 4 == 0 && i % 100 != 0 || i % 400 == 0) {
                    //闰年
                    timeDistance += 366;
                } else {
                    //不是闰年
                    timeDistance += 365;
                }
            }
            return timeDistance + (day2 - day1);
        } else {
            //不同年
            System.out.println("判断day2 - day1 : " + (day2 - day1));
            return day2 - day1;
        }
    }


    public static void input(CharSequence s, EditText et_num, double minNum, String minTip) {
        if (s.toString().contains(".")) {
            if (s.length() == 1) {
                et_num.setText("");
                return;
            }
            if (s.length() - 1 - s.toString().indexOf(".") > 3) {
                s = s.toString().subSequence(0,
                        s.toString().indexOf(".") + 4);
                et_num.setText(s);
                et_num.setSelection(s.length());
            }
        } else {
            if (s.length() > 6) {
                et_num.setText(s.subSequence(0, 6));
                et_num.setSelection(s.length() - 1);
            }
        }
        if (s.toString().trim().equals(".")) {
            s = "0" + s;
            et_num.setText(s);
            et_num.setSelection(3);
        }
        if (s.toString().startsWith("0")
                && s.toString().trim().length() > 1) {
            if (!s.toString().startsWith(".", 1)) {
                et_num.setText(s.subSequence(0, 1));
                et_num.setSelection(1);
                return;
            }
        }
        try {
            if (Double.parseDouble(s.toString()) < minNum) {
                MToast.showToast(UiUtil.getContext(), minTip);
                et_num.setText(minNum + "");
                et_num.setSelection(et_num.getText().toString().length());
                return;
            } else {

            }
        } catch (Exception e) {

        }
    }

    public static void input2(CharSequence s, EditText et_num, double minNum, String minTip) {
        if (s.toString().contains(".")) {
            if (s.length() == 1) {
                et_num.setText("");
                return;
            }
            if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                s = s.toString().subSequence(0,
                        s.toString().indexOf(".") + 3);
                et_num.setText(s);
                et_num.setSelection(s.length());
            }
        } else {
            if (s.length() > 6) {
                et_num.setText(s.subSequence(0, 6));
                et_num.setSelection(s.length() - 1);
            }
        }
        if (s.toString().trim().equals(".")) {
            s = "0" + s;
            et_num.setText(s);
            et_num.setSelection(2);
        }
        if (s.toString().startsWith("0")
                && s.toString().trim().length() > 1) {
            if (!s.toString().startsWith(".", 1)) {
                et_num.setText(s.subSequence(0, 1));
                et_num.setSelection(1);
                return;
            }
        }
        try {
            if (Double.parseDouble(s.toString()) < minNum) {
                MToast.showToast(UiUtil.getContext(), minTip);
                et_num.setText(minNum + "");
                et_num.setSelection(et_num.getText().toString().length());
                return;
            } else {

            }
        } catch (Exception e) {

        }
    }


    public static void calculate(BaseViewHolder helper, EditText et_num, int type, double min, double max, String minTip, String maxTip) {
        try {
            String s = et_num.getText().toString();
            double num = Double.parseDouble(s);
            if (type == 0) {
                num--;
                if (num < min) {
                    MToast.showToast(UiUtil.getContext(), minTip);
                    return;
                }
            } else {
                num++;
                if (num > max) {
                    MToast.showToast(UiUtil.getContext(), maxTip);
                    return;
                }
            }
            et_num.setText(num + "");
        } catch (Exception e) {
            MToast.showToast(UiUtil.getContext(), "输入错误");
        }
    }

    public static boolean isEmpty(String s) {
        if (s == null || TextUtils.isEmpty(s)) {
            return true;
        } else {
            return false;
        }
    }


    /**
     * 设置状态栏是否为浅色模式
     *
     * @param activity
     * @param isLightMode
     */
    public static void setStatusBarLightMode(Activity activity,
                                             final boolean isLightMode) {
        setStatusBarLightMode(activity.getWindow(), isLightMode);
    }

    public static void setStatusBarLightMode(Window window,
                                             final boolean isLightMode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            View decorView = window.getDecorView();
            int vis = decorView.getSystemUiVisibility();
            if (isLightMode) {
                vis |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            } else {
                vis &= ~View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
            }
            decorView.setSystemUiVisibility(vis);
        }
    }

    // 判断为null并拦截
    public static void showTipToastReturn(String keyStr, String tipStr) {
        if (UiUtil.isEmpty(keyStr)) {
            UiUtil.showToast(tipStr);
            return;
        }
    }

    /**
     * 返回"" 禁止输入
     * 返回null 不限制输入
     */
    public static void getInputFilter(EditText editText, int digits) {
        editText.setKeyListener(DigitsKeyListener.getInstance("0123456789."));
        // 控制输入框的小数位和长度,这里长度暂时设置为10
        editText.setFilters(new InputFilter[]{new InputFilter() {

            /**
             * @param source 用户当前输入的内容
             * @param start
             * @param end
             * @param dest 原有数据
             * @param dstart
             * @param dend
             * @return
             */
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                // 删除等特殊字符，直接返回
                if ("".equals(source.toString())) {
                    return null;
                }
                String dValue = dest.toString();
                if (TextUtils.isEmpty(dValue) && source.toString().equals(".")) {
                    return "0.";
                }
                Matcher m = Pattern.compile("[0-9]*").matcher(source);   //除数字外的其他的
                if (dValue.contains(".")) {
                    //已经存在小数点的情况下，只能输入数字
                    if (!m.matches()) {
                        return "";
                    }
                } else {
                    //未输入小数点的情况下，可以输入小数点和数字
                    if (!m.matches() && !source.equals(".")) {
                        return null;
                    }
                }
                String[] splitArray = dValue.split("\\.");
                if (splitArray.length > 1) {
                    String dotValue = splitArray[1];
                    int diff = dotValue.length() + 1 - digits;
                    if (diff > 0) {
                        return source.subSequence(start, end - diff);
                    }
                }
                return null;
            }
        }});
    }

    /**
     * 倒计时
     *
     * @param endTime
     */
    public static GoodsTimerUtils timer;

    public static void startTimer(long startTime, long endTime, TextView timeTip, TextView timeTv,
                                  LinearLayout timerLayout, TextView day, TextView tv_day,
                                  TextView tv_hours, TextView tv_minutes, TextView tv_seconds, int status,int position) {
        long nowTime = System.currentTimeMillis();
        long startTime1 = startTime - nowTime;
        if (status == 1) {
            if (startTime1 / 86400000 >= 3) {
                timerLayout.setVisibility(View.GONE);
                timeTip.setVisibility(View.GONE);
            } else {
                timerLayout.setVisibility(View.VISIBLE);
                timeTip.setVisibility(View.VISIBLE);
                timeTip.setText("距离开始还有");
                timeTv.setVisibility(View.GONE);
                timerLayout.setVisibility(View.VISIBLE);
                if (timer != null) {
                    timer.cancel();
                }
                timer = new GoodsTimerUtils(startTime1, day, tv_day, tv_hours, tv_minutes, tv_seconds,position); //倒计时
                timer.start();
            }

        } else {
            long time = endTime - nowTime;
            if (time <= 0) {
                return;
            }
            timeTip.setVisibility(View.VISIBLE);
            if (time / 86400000 >= 7) {
                timerLayout.setVisibility(View.GONE);
                timeTip.setText("促销至");
                timeTv.setVisibility(View.VISIBLE);
                timeTv.setText(get3Time(endTime));
            } else {
                timeTip.setText("距离结束还剩");
                timeTv.setVisibility(View.GONE);
                timerLayout.setVisibility(View.VISIBLE);
                if (timer != null) {
                    timer.cancel();
                }
                timer = new GoodsTimerUtils(time, day, tv_day, tv_hours, tv_minutes, tv_seconds,position); //倒计时
                timer.start();
            }
        }
    }
    public static CountDownTimer timerP;
    public static void startPopTimer(long startTime, long endTime, int promoteStatus, TextView timeTv) {
        long nowTime = System.currentTimeMillis();
        long startTime1 = startTime - nowTime  ;
        if (promoteStatus==1) {
            if (startTime1 / 86400000 >= 3) {
                timeTv.setVisibility(View.GONE);
            } else {
                setTimerP(startTime1,promoteStatus,timeTv);
            }
        }else {
            long time = endTime - nowTime;
            if (time <= 0) {
                return;
            }
            if (time / 86400000 >= 7) {
                timeTv.setText("(促销至 "+get3Time(endTime)+")");
            } else {
                setTimerP(time,promoteStatus,timeTv);
            }
        }
    }
    private static void setTimerP(long time,int promoteStatus,TextView timeTv){
        if (timerP!=null){
            timerP.cancel();
        }
        timerP = new CountDownTimer(time, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                long dd = millisUntilFinished / 1000 / 86400;//天
                long hh = millisUntilFinished / 1000 % 86400 / 3600;                 //转换小时
                long mm = millisUntilFinished / 1000 % 86400 % 3600 / 60;            //转换分钟
                long ss = millisUntilFinished / 1000 % 86400 % 3600 % 60;            //剩余秒数
                if (dd > 0) {
                    if (promoteStatus==1) {
                        timeTv.setText("(距离开始还有：" + dd + "天" + hh + "小时" + mm + "分" + ss + "秒)");
                    }else {
                        timeTv.setText("(距离结束还剩：" + dd + "天" + hh + "小时" + mm + "分" + ss + "秒)");
                    }
                } else {
                    if (promoteStatus==1) {
                        timeTv.setText("(距离开始还有：" + hh + "小时" + mm + "分" + ss + "秒)");
                    }else {
                        timeTv.setText("(距离结束还剩：" + hh + "小时" + mm + "分" + ss + "秒)");
                    }
                }

            }
            @Override
            public void onFinish() {
            }
        };
        timerP.start();
    }

}
